let allPatches
let index = 0

function patch(node, patches){
    allPatches = patches
    walkpatch(node)
}

function walkpatch(node){
    let currentPatch = allPatches[index++]
    let childNodes = node.childNodes
    childNodes.forEach(child => walkpatch(child))
    if(currentPatch){
        doPatch(node, currentPatch)
    }
}

function doPatch(node, patches){
    patches.forEach(patch => {
        switch(patch.type){
            case 'ATTRS':
                for(let key in patch.attrs){
                    if(patch.attrs[key]){
                        setAttr(node, key, patch.attrs[key])
                    }else{
                        node.removeAttribute(key)
                    }
                }
                break
            case 'TEXT':
                node.textContent = patch.text
                break
            case 'REMOVE':
                node.parentNode.removeChild(node)
                break
            case 'REPLACE':
                let newNode = (patch.newNode instanceof Element) ? 
                    render(patch.newNode) : document.createTextNode(patch.newNode)
                node.parentNode.replaceChild(newNode, node)
                break
        }
    })
}